import cv2, os, sys
from pathlib import Path
from common.config import DATA_PATH
from common.file_operation import ExcelOperation

class GetImagePoints(object):
    flag = True

    def __init__(self, file_path):
        self.file_path=file_path
        self.points=[]
        self.points_list = []
        self.img=None


    def get_image_points(self):
        def on_EVENT_LBUTTONDOWN(event, x, y, flags, param):
            # print(self.points)
            if event == cv2.EVENT_LBUTTONDOWN:
                xy = "[%f,%f]" % (x/width*100, y/height*100)
                self.points.append(xy)
                cv2.circle(self.img, (x, y), 1, (255, 0, 0), thickness = -1)
                pixel="(%d, %d)"%(x,y)
                cv2.putText(self.img, pixel, (x, y), cv2.FONT_HERSHEY_PLAIN,
                            1.0, (0,0,0), thickness = 1)
                cv2.imshow(os.path.join(image_path, image_name), self.img)
            if event == cv2.EVENT_RBUTTONDOWN:
                # 右击后进入下一个区域的画线操作，并将前一个画线区域的点首尾重合，成为封闭区域
                self.points.append(self.points[0])
                # print(f"27 self.points: {self.points}")
                # 将每个点的像素点位置通过“|”拼接起来，生成字符串
                points_string = ",".join(str(ele) for ele in self.points)
                # 将当前点位置的字符串作为元素，追加到当前图片的点列表中
                self.points_list.append(points_string)
                self.points.clear()


        for item in Path(self.file_path).rglob('*.jpg'):
            image_path=Path(item).parent
            image_name=Path(item).name
            video_name=f"{Path(item).stem}.mp4"

            self.img = cv2.imread(os.path.join(image_path, image_name))
            height=self.img.shape[0]
            width=self.img.shape[1]
            self.points_list.append(f"[{width},{height}]")

            flag=True
            while flag:
                cv2.namedWindow(os.path.join(image_path, image_name), flags=cv2.WINDOW_NORMAL)
                cv2.setMouseCallback(os.path.join(image_path, image_name), on_EVENT_LBUTTONDOWN)
                cv2.imshow(os.path.join(image_path, image_name), self.img)
                cv2.waitKey(0)
                cv2.destroyAllWindows()

                # print(f"48 self.points: {self.points}")
                # 回车后退出当前图片的画线操作，并将前一个画线区域的点首尾重合，成为封闭区域
                self.points.append(self.points[0])
                # print(f"51 self.points: {self.points}")
                points_string = ",".join(str(ele) for ele in self.points)
                # 将当前点位置的字符串作为元素，追加到当前图片的点列表中
                self.points_list.append(points_string)
                # print(f"points_string: {points_string}")
                # print(f"self.points_list: {self.points_list}")
                self.points.clear()

                while True:
                    answer=input(f"Are you sure to store these points {self.points_list}?(y/n)")
                    if answer=="y":
                        flag=False
                        print("yes")
                        break
                    elif answer=="n":
                        print("no")
                        self.points_list.clear()
                        self.points_list.append(f"[{width},{height}]")
                        self.points.clear()
                        # 此时窗口已消失，无需销毁
                        # cv2.destroyWindow(os.path.join(image_path, image_name))
                        self.img = cv2.imread(os.path.join(image_path, image_name))
                        cv2.namedWindow(os.path.join(image_path, image_name), flags=cv2.WINDOW_NORMAL)
                        cv2.imshow(os.path.join(image_path, image_name), self.img)
                        break
                    else:
                        print("What you input is invalid.")

            excel=ExcelOperation(os.path.join(DATA_PATH, "video_info.xlsx"))
            self.points_list.insert(0, video_name)
            print(f"data to be written: {self.points_list}")
            # if GetImagePoints.flag:
            #     excel.clear_data(locate="add", start_row=2)
            #     GetImagePoints.flag=False
            excel.write_data(locate="add", data=self.points_list)
            self.points_list.clear()

if __name__=="__main__":
    instan=GetImagePoints("F:\\05_autotest_proj\\auto_get_video_pixel\\data")
    instan.get_image_points()